<template>
	<div class="picturemanagement">
		<Nav></Nav>
		<div class="writing_right">
			<div class="TitleList">
				<div class="TitleList_padding">
					<div class="TitleList_top">
						<div class="TitleList_top_title"><span></span>我的图片</div>
						<div class="TitleList_top_txt">
							<div class="top_txt_dd">
								<button @click="UploadPicture = true;showUpload = true">批量上传</button>
							</div>
							<div class="top_txt_dt">
								<div class="txt_dt_list">
									<div class="dt_list_left">分类</div>
									<el-select clearable v-model="class_type" placeholder="默认分类">
										<el-option v-for="item in class_types" :key="item.id" :label="item.name"
											:value="item.id">
										</el-option>
									</el-select>
									<div class="dt_list_icon" @click="showClass"><img src="@a/img/sv4.svg" /></div>
								</div>
								<div class="txt_dt_search">
									<div class="dt_search_left">
										<span><i class="el-icon-search"></i></span>
										<input type="text" v-model="keywords" placeholder="搜索标题" />
									</div>
									<div class="dt_search_right" @click="search">搜索</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="picturemanagement_content">
					<div class="picturemanagement_content_nav">
						<div class="content_nav_left">
							<label>
								<input type="checkbox" v-model="selectAll" @change="selectAllItems" />
								全选
							</label>
						</div>
						<div class="content_nav_right">
							<div class="nav_right_list notBlue" @click="batchDelete">批量删除</div>
							<div class="nav_right_list notBlue" @click="showChangeClass=true">移动分类</div>
						</div>
					</div>
					<div class="picturemanagement_content_top" v-loading="loading"
						element-loading-spinner="el-icon-loading" element-loading-text="拼命加载中"
						element-loading-background="rgba(255, 255, 255, 1)">
						<div class="content_top_list" v-for="(info, index) in infos.data" :key="index">
							<div class="top_list_img">
								<el-image :src="info.filepath" :preview-src-list="[info.filepath]">
								</el-image>
							</div>
							<label class="top_list_btn">
								<input type="checkbox" v-model="info.checked" @change="checkSelectAll" />
							</label>
							<div class="top_list_txt">
								<div class="list_txt_left">
									<div class="txt_left_dd">分类：{{ info.imgClass.name }}</div>
									<div class="txt_left_dt">{{ info.name }}</div>
								</div>
								<div class="list_txt_close" @click="deleteItem(index)"><i class="el-icon-close"></i>删除
								</div>
							</div>
						</div>

						<div class="not_data not_data2" v-show="infos.data.length === 0">
							<div class="not_data_icon"><img src="@a/img/bg26.jpg" /></div>
							<div class="not_data_title">暂无图片</div>
						</div>
					</div>


					<div class="page">
						<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
							:current-page="infos.current_page" :page-sizes="per_pages" :page-size="infos.per_page"
							layout="total, sizes, prev, pager, next, jumper" :total="infos.total">
						</el-pagination>
					</div>
				</div>
			</div>
		</div>


		<div class="CategorySettings" v-show="show">
			<div class="CategorySettings_content">
				<div class="CategorySettings_content_title">
					<div class="content_title_dd"><span></span>分类设置</div>
					<div class="content_title_dt" @click="show = !show"><i class="el-icon-close"></i></div>
				</div>
				<div class="CategorySettings_content_txt">
					<div class="content_txt_title">
						<div class="txt_title_list">序号</div>
						<div class="txt_title_list">排序</div>
						<div class="txt_title_list">名称</div>
					</div>
					<div class="content_txt_table">
						<div class="txt_table_scro">
							<div class="txt_table_list" v-for="(tab, index) in class_types" :key="index">
								<div class="table_list_li">{{ index + 1 }}</div>
								<div class="table_list_li ToSort" :class="{ active: tab.isActive }">
									{{ tab.sort }}
									<input type="text" v-model="tab.sort" />
								</div>
								<div class="table_list_li Name" :class="{ active: tab.isActive }">
									<div class="list_li_name">{{ tab.name_all }}</div>
									<input type="text" v-model="tab.name" />
								</div>
								<div class="table_list_operate" :class="{ active: tab.isActive }">
									<div class="list_operate_li" @click="toggleActive2(index)">
										<img src="@a/img/sv5.svg" />
										<span v-if="!tab.isActive">编辑</span>
										<span v-if="tab.isActive">保存</span>
									</div>
									<div class="list_operate_li" @click="deleteInfo2(index)"><img
											src="@a/img/sv6.svg" />删除</div>
								</div>
							</div>
						</div>
						<div class="txt_table_add">
							<div class="table_add_btn" @click="addItem">增加信息+</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 转移分类 -->
		<div class="batchRelease" v-show="showChangeClass">
			<div class="Preview_content">
				<div class="Preview_content_title">
					<div class="content_title_left"><span></span>转移分类</div>
					<div class="content_title_right" @click="showChangeClass = !showChangeClass"><i
							class="el-icon-close"></i></div>
				</div>
				<div class="Edit_content">

					<div class="Edit_content_list">
						<div class="content_list_dd">目标分类</div>
						<div class="content_list_dt">
							<el-select v-model="change_class" placeholder="请选择要转移到哪个分类里">
								<el-option v-for="item in class_types" :key="item.id" :label="item.name_all"
									:value="item.id">
								</el-option>
							</el-select>
						</div>
					</div>



				</div>
				<div class="Edit_btn">
					<button class="back" @click="showChangeClass = !showChangeClass">返回</button>
					<button class="save" @click="setChangeClass">开始转移</button>
				</div>
			</div>
		</div>
		<!-- 批量上传 -->
		<div class="UploadPicture" :class="{ active: !this.showUpload }" v-show="UploadPicture">
			<div class="Preview_content">
				<div class="Preview_content_title">
					<div class="content_title_left"><span></span>
						<div v-show="showUpload">批量上传</div>
						<div v-show="!showUpload">上传中</div>
					</div>
					<div class="content_title_right" @click="closeUplodaWindow"><i class="el-icon-close"></i></div>
				</div>
				<div class="UploadPicture_content">
					<div class="UploadPicture_content_top" v-show="showUpload">
						<div class="content_top_dd">选择分类</div>
						<div class="content_top_dt">
							<el-select v-model="class_type2" placeholder="默认分类">
								<el-option v-for="item in class_types" :key="item.id" :label="item.name"
									:value="item.id">
								</el-option>
							</el-select>
						</div>
					</div>
					<div class="UploadPicture_content_bottom">
						<el-upload class="upload-demo" ref="upload"  :action="this.baseURL + 'api/fileManager/upload'" :before-upload="beforeUpload"
							:on-success="handleSuccess" :on-error="handleError" :file-list="fileList" :multiple="true"
							:data="{'class_id': class_type2}" drag :drag-over-class="'dragover'"
							@dragover.native.prevent>
							<i class="el-icon-upload" v-show="showUpload"></i>
							<div class="el-upload__text" v-show="showUpload">将文件拖到此处，或<em>点击上传</em></div>
							<div class="el-upload__tip" slot="tip" v-show="showUpload">
								只能上传{{ config.fileExt}}文件，且不超过{{ config.fileSize }}kb</div>
						</el-upload>
					</div>
					<div class="uploadBar"><div :style="'width:'+(fileList.length/addFileCount)*100+'%'"></div></div>
				</div>
			</div>
		</div>


		<!-- 充值弹窗 -->
		<rechargeWindow v-if="rechargeShow" @close="rechargeShow = false"></rechargeWindow>

	</div>
</template>

<script>
	import {
		Message,
		MessageBox
	} from 'element-ui';
	import Nav from "@c/common/nav/nav";
	import rechargeWindow from "@c/common/rechargeWindow/rechargeWindow";

	export default {
		name: "pictureManagement",
		data() {
			return {
				config: {
					'fileExt': '',
					'fileSize': ''
				},
				rechargeShow: false,
				infos: {
					data: [],
					per_page: 24,
					current_page: 1,
					last_page: 1,
					total: 0
				},
				keywords: '',
				per_pages: [24, 50, 100, 200],
				class_types: [],
				class_type: '',
				class_type2: '',
				UploadPicture: false,
				showUpload: true,
				srcList: [
					require("@a/img/bg5.jpg"),
					require("@a/img/bg6.jpg"),
					require("@a/img/bg7.jpg"),
					require("@a/img/bg8.jpg")
				],
				input: '',
				token: localStorage.getItem('token'),
				show: false,
				fileList: [],
				loading: true,
				selectAll: false, // 全选状态，默认为false
				showChangeClass: false,
				change_class: null,
				uploadQueue: [], // 用于文件上传的队列
				isUploading: false, // 用于跟踪上传是否正在进行的标志
				addFileCount:0,//选中的文件数量
			};
		},
		components: {
			Nav,
			rechargeWindow
		},

		methods: {
			selectAllItems() {
				// 更新所有子复选框的选中状态为全选按钮的状态
				this.infos.data.forEach((info) => {
					info.checked = this.selectAll;
				});
			},
			checkSelectAll() {
				// 检查是否所有子复选框都选中
				this.selectAll = this.infos.data.every((info) => info.checked);
			},
			//批量删除
			batchDelete() {
				// 找出所有选中的项的索引
				const selectedIndexes = this.infos.data
					.map((info, index) => (info.checked ? index : null))
					.filter((index) => index !== null);

				if (selectedIndexes.length === 0) {
					// 如果没有选中的项，则不执行删除操作
					return;
				}
				// 弹出确认对话框
				MessageBox.confirm('确定要删除选中的图片吗？', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					.then(() => {
						this.loading=true;
						let ids = []
						// 用户点击了确定按钮，执行删除操作
						for (let i = 0; i < selectedIndexes.length; i++) {
							var choice_index = selectedIndexes[i]
							var id = this.infos.data[choice_index].id
							ids.push(id);

						}
						//执行删除
						this.axios.post('/api/fileManager/delete', {
							id: ids
						}).then((res) => {
							this.loading=false;
							// 重置全选按钮状态为false
							this.selectAll = false;
							this.getList()
						})

					})
					.catch(() => {
						// 用户点击了取消按钮，不执行删除操作
					});
			},
			//移动分类
			setChangeClass() {
				// 找出所有选中的项的索引
				const selectedIndexes = this.infos.data
					.map((info, index) => (info.checked ? index : null))
					.filter((index) => index !== null);
				let ids = []
				// 用户点击了确定按钮，执行删除操作
				for (let i = 0; i < selectedIndexes.length; i++) {
					var choice_index = selectedIndexes[i]
					var id = this.infos.data[choice_index].id
					ids.push(id);

				}
				this.axios.post('/api/fileManager/changeClass', {
					ids: ids,
					img_class_id: this.change_class,
				}).then(res => {
					if (res.code === 1) {
						this.$message.success('转移成功');
						this.getList()
						this.showChangeClass = false;
					}
				})
			},
			search() {
				this.infos.current_page = 1;
				this.getList()
			},

			getConfig() {
				let that = this;
				this.axios.get('/api/fileManager/getConfig').then(res => {
					that.config = res.result
				})
			},
			//分页
			handleSizeChange(val) {
				this.infos.per_page = val
				this.getList()
			},
			handleCurrentChange(val) {
				this.infos.current_page = val
				this.getList()

			},
			closeUplodaWindow() {
				this.UploadPicture = false;
				this.fileList=[];
				this.uploadQueue=[];
				this.getList()
			},
			getList() {
				// loading 开始
				this.loading = true;

				let that = this;
				that.axios.get('/api/fileManager/list', {
					params: {
						page: that.infos.current_page,
						keywords: that.keywords,
						list_rows: that.infos.per_page,
						class_id: that.class_type
					}
				}).then(res => {
					// loading结束
					this.loading = false;

					that.infos = res.result;
				})
			},
			showClass() {
				this.getImgClass();
				this.show = !this.show
			},
			getImgClass() {
				let that = this;
				this.axios.get('/api/imgClass/list').then(res => {
					res.result.forEach(item => {
						item.isActive = false
					})
					that.class_types = res.result
				})
			},
			//点击增加信息
			addItem() {
				this.class_types.push({
					id: 0,
					ToSort: 0,
					name: '',
					isActive: true
				});
			},
			//标题列表保存、编辑
			toggleActive(index) {
				this.tableList.forEach((info, i) => {
					if (i === index) {
						info.isActive = !info.isActive;
					}
				});
			},
			//分类设置保存、编辑
			toggleActive2(index) {
				let that = this;
				let thisData = this.class_types[index];
				// 新增或修改
				if (thisData.isActive) {
					if (thisData.id == 0) {
						//新增
						that.axios.post('/api/imgClass/add', {
							name: thisData.name,
							sort: thisData.sort ? thisData.sort : 0
						}).then(res => {
							if (res.code == 1) {
								that.getImgClass()
								that.class_type = ''
								Message.success('新增成功！')
							}
						})
					} else {
						//修改
						that.axios.post('/api/imgClass/update', {
							id: thisData.id,
							name: thisData.name,
							sort: thisData.sort
						}).then(res => {
							if (res.code == 1) {
								that.getImgClass()
								Message.success('修改成功！')
							}
						})
					}
				}
				this.class_types[index].isActive = !thisData.isActive
			},
			//分类设置删除
			deleteInfo2(index) {
				let that = this;
				const item = this.class_types[index];
				MessageBox.confirm(`确定删除${item.name}吗？`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					that.axios.post('/api/imgClass/delete', {
						id: item.id
					}).then(res => {
						if (res.code == 1) {
							that.class_type = '';
							this.$message({
								type: 'success',
								message: '删除成功!'
							});
							that.getImgClass()
						}
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
					// 用户点击取消或者弹窗关闭时不做任何操作
				});
			},
			//上传
			beforeUpload(file) {
				this.addFileCount++;
				var isOk = true;
				let typeArr = this.config.fileExt.split(',');
				let isImg = false;
				for (let i in typeArr) {
					if (file.type === `image/${typeArr[i]}`) {
						isImg = true;
					}
				}
				
				// const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
				if (!isImg) {
					this.handleError(`只能上传 ${this.config.fileExt} 文件！`, file);
					file.status='fail';
					this.fileList.unshift(file);
					this.$message.error(file.name + `只能上传 ${this.config.fileExt} 文件！`);
					return false;
				}
				const isLt500K = file.size / 1024 < this.config.fileSize;
				if (!isLt500K) {
					this.handleError(`文件大小不能超过 ${this.config.fileSize}KB！`, file);
					file.status='fail';
					this.$message.error(file.name + `上传失败：文件大小不能超过 ${this.config.fileSize}KB！`);
					return false;
				}
				if (isOk) {
					this.uploadQueue.push(file);
					// 如果已经有上传在进行中，将这个文件加入队列
					if (!this.isUploading) {
						
						this.isUploading = true;
						this.uploadFile();
					}

				}
				return false;
			},

			uploadFile() {
				let file = this.uploadQueue[0];
				//上传完毕
				if (!file) {
					this.isUploading = false;
					return;
				}
				const formData = new FormData();
				formData.append('file', file);
				formData.append('class_id', this.class_type2);
				// try {
				const response = this.axios.post(
					'/api/fileManager/upload',
					formData, {
						headers: {
							'Authorization': this.token,
							'Content-Type': 'multipart/form-data', // 设置请求头部，指定数据为文件上传
						},
					}
				).then(
					res => {
						file.status='success';
						this.fileList.unshift(file);
						//这个上传结束了
						this.uploadQueue.splice(0, 1);
						this.uploadFile();
					}
				);

			},
			handleError(msg, file) {
				file.status = 'fail'; // 设置上传状态为失败
				file.response = msg; // 将错误信息保存在文件对象的 response 属性中
			},
			handleSuccess(msg, file) {
				file.status = 'success'; // 设置上传状态为成功
			},
			//删除
			deleteItem(index) {
				let that = this;
				const item = this.infos.data[index];
				MessageBox.confirm(`确定删除${item.name}吗？`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					that.loading=true;
					that.axios.post('/api/fileManager/delete', {
						id: item.id
					}).then(
						res => {
							if (res.code == 1) {
								that.getList()
								this.$message({
									type: 'success',
									message: '删除成功!'
								});
							}

						}
					)




					// 用户点击确定后执行删除操作
					// this.infos.splice(index, 1);
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
					// 用户点击取消或者弹窗关闭时不做任何操作
				});
			},
		},
		created() {
			this.getConfig();
			this.getImgClass();
			this.getList();
		},
		mounted() {

		},
	}
</script>

<style>
	@import "pictureManagement.css";
</style>